<template>
  <px-button v-has="'ALL_ALERT_DOWN_RULES_ADD'" type="primary" style="margin-bottom: 8px" @click="isDrawerShow = true">新建报警下线规则</px-button>
  <px-table :data="tableData" class="spare-parts-table" height="calc(100vh - 288px)" border>
    <px-table-column prop="ruleName" label="名称" min-width="180" show-overflow-tooltip />
    <px-table-column prop="classNameDesc" label="科室" min-width="100" show-overflow-tooltip />
    <px-table-column prop="shieldCondition" label="下线点位" min-width="100" show-overflow-tooltip>
      <template #default="scope">
        <px-button type="primary" link @click="handleShowPointList(scope.row)">查看</px-button>
      </template>
    </px-table-column>
    <!-- 生效时间按照创建时间来 -->
    <px-table-column prop="createTime" label="生效时间" min-width="180" show-overflow-tooltip />
    <px-table-column prop="status" label="状态">
      <template #default="scope">
        <div class="status">
          <div :class="['circle', scope.row.enableStatus === 'ON' ? 'green' : 'red']" />
          <div :style="{ color: scope.row.enableStatus === 'ON' ? '#10B981' : '#EF4444' }">
            {{ scope.row.enableStatus === "ON" ? "启用" : "停用" }}
          </div>
        </div>
      </template>
    </px-table-column>
    <px-table-column label="操作" min-width="100" class-name="small-padding fixed-width">
      <template #default="scope">
        <px-tooltip content="编辑" placement="top">
          <px-button v-has="'ALL_ALERT_DOWN_RULES_EDIT'" link type="primary" icon="EditPen" @click="handleUpdate(scope.row)" />
        </px-tooltip>
        <px-tooltip :content="scope.row.enableStatus === 'OFF' ? '启用' : '禁用'" placement="top">
          <px-button
            v-has="'ALL_ALERT_DOWN_RULES_ABLE'"
            link
            :type="scope.row.enableStatus === 'ON' ? 'warning' : 'success'"
            :icon="scope.row.enableStatus === 'ON' ? 'CircleClose' : 'CircleCheck'"
            @click="handleEnable(scope.row)"
          />
        </px-tooltip>
        <px-tooltip content="删除" placement="top">
          <px-button v-has="'ALL_ALERT_DOWN_RULES_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
        </px-tooltip>
      </template>
    </px-table-column>
  </px-table>
  <pagination
    v-show="total > 0"
    v-model:page="queryParams.pageNum"
    v-model:limit="queryParams.pageSize"
    class="equip-table-pagination"
    :total="total"
    @pagination="queryTable"
  />

  <!--新建报警规则-->
  <px-dialog
    v-model="isDrawerShow"
    :title="isEdit ? '修改报警下线规则' : '新建报警下线规则'"
    destroy-on-close
    width="80%"
    class="alert-rule-dialog"
    @close="handelCancel"
  >
    <px-form ref="formRef" :model="form" label-position="right" label-width="140px" :rules="rules">
      <EquipClassSelect :className="form.className" :isDisabled="isEdit" @changeClassName="changeClassName" />
      <px-form-item label="规则名称" prop="ruleName">
        <px-input v-model="form.ruleName" placeholder="请输入报警下线规则名称" maxlength="50" show-word-limit />
      </px-form-item>
      <px-form-item label="规则描述">
        <px-input
          v-model="form.ruleDesc"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 6 }"
          maxlength="1000"
          show-word-limit
          placeholder="请输入规则描述"
        />
      </px-form-item>
      <px-form-item label="下线点位">
        <div style="display: flex">
          <px-button type="primary" plain style="width: 100px; margin-bottom: 10px" :disabled="!form.className" @click="isPointShow = true">
            选择点位
          </px-button>
          <px-button plain type="danger" :disabled="selectPointData.length === 0" @click="handleBatchDeletePoint"> 批量删除 </px-button>
        </div>
        <px-table :data="selectPointData" class="equip-table" size="small" max-height="300px" border @selection-change="selectionPointChange">
          <px-table-column type="selection" min-width="40" align="center" />
          <!-- <px-table-column type="index" label="序号" min-width="56" /> -->
          <px-table-column prop="point" label="报警点位" width="300" show-overflow-tooltip />
          <px-table-column prop="alarmLevel" label="报警级别" show-overflow-tooltip>
            <template #default="scope">
              <px-tag v-if="scope.row.alarmLevel" style="color: #fff" round :color="tagBgColorList[scope.row.alarmLevel]">
                {{ scope.row.alarmLevel }}
              </px-tag>
              <span v-else />
            </template>
          </px-table-column>
          <px-table-column prop="alarmType" label="报警类型" show-overflow-tooltip />
          <px-table-column prop="alarmDesc" label="报警描述" show-overflow-tooltip />
          <px-table-column prop="classNameDesc" label="科室" show-overflow-tooltip />
          <px-table-column prop="systemName" label="系统" width="160" show-overflow-tooltip />
          <px-table-column prop="twinName" label="所属设备" show-overflow-tooltip />
          <px-table-column prop="twinPosition" label="位置" show-overflow-tooltip />
          <px-table-column fixed="right" label="操作" min-width="64" align="center">
            <template #default="scope">
              <px-tooltip content="删除" placement="top">
                <px-button link type="danger" icon="Delete" @click="handleDeletePoint(scope.$index)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
      </px-form-item>
      <px-form-item label="下线生效时间范围" prop="isForeverShield">
        <div class="flex flex-col">
          <div>
            <px-radio-group v-model="form.isForeverShield">
              <px-radio label="YES">永久下线</px-radio>
              <px-radio label="NO">指定时间范围</px-radio>
            </px-radio-group>
            <px-radio-group v-show="form.isForeverShield === 'NO'" v-model="form.timeRangeType">
              <px-radio label="ABSOLUTE">绝对时间范围</px-radio>
              <px-radio label="RELATIVE">相对时间范围</px-radio>
            </px-radio-group>
          </div>
          <div v-if="form.timeRangeType === 'ABSOLUTE' && form.isForeverShield === 'NO'">
            <px-date-picker
              v-model="form.date"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </div>
          <div v-if="form.timeRangeType === 'RELATIVE' && form.isForeverShield === 'NO'">
            <!-- <px-date-picker
              v-model="form.date"
              format="HH:mm:ss"
              value-format="HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            /> -->
            <px-time-picker
              v-model="form.date"
              value-format="YYYY-MM-DD HH:mm:ss"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
            <!-- <px-checkbox v-model="form.isCycleTime" label="循环日期（不勾选则对所有日期生效）" /> -->
          </div>
        </div>
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="handelCancel">取消</px-button>
        <px-button type="primary" @click="handleSubmit(formRef)">确定</px-button>
      </span>
    </template>
    <PointDialog :visible="isPointShow" :className="form.className" @closeDialog="closeDialog" />
  </px-dialog>
  <px-dialog v-model="isTablePointShow" title="下线点位列表" width="1200" :before-close="handleCloseTablePoint">
    <px-table :data="pointData" class="equip-table" max-height="400" border>
      <px-table-column prop="point" label="报警点位" min-width="150" show-overflow-tooltip />
      <px-table-column prop="alarmLevel" label="报警级别" min-width="100" show-overflow-tooltip>
        <template #default="scope">
          <px-tag v-if="scope.row.alarmLevel" style="color: #fff" round :color="tagBgColorList[scope.row.alarmLevel]">
            {{ scope.row.alarmLevel }}
          </px-tag>
          <span v-else />
        </template>
      </px-table-column>
      <px-table-column prop="alarmType" label="报警类型" min-width="100" show-overflow-tooltip />
      <px-table-column prop="alarmDesc" label="报警描述" min-width="100" show-overflow-tooltip />
      <px-table-column prop="classNameDesc" label="科室" min-width="80" show-overflow-tooltip />
      <px-table-column prop="systemName" label="系统" min-width="100" show-overflow-tooltip />
      <px-table-column prop="twinId" label="设备ID" min-width="150" show-overflow-tooltip />
      <px-table-column prop="twinName" label="所属设备" min-width="150" show-overflow-tooltip />
      <px-table-column prop="twinPosition" label="位置" min-width="150" show-overflow-tooltip />
    </px-table>
  </px-dialog>
</template>
<script lang="ts" setup>
import { addShieldRulesApi, deleteShieldRulesApi, queryShieldRuleByRuleId, queryShieldRulesListApi, updateShieldRulesApi } from "@/api/alert";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRaw, toRefs } from "vue";
import PointDialog from "./PointDialog.vue";

const formRef = ref();
const { proxy }: any = getCurrentInstance();

const data = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableData: [],
  total: 0,
  form: {},
  isDrawerShow: false,
  isPointShow: false,
  isEdit: false, // 是否是编辑
  rules: {
    ruleName: [{ required: true, message: "请输入报警下线规则名称", trigger: ["blur"] }],
    isForeverShield: [{ required: true, message: "请选择要下线生效时间范围", trigger: ["blur", "change"], validator: checkDate }]
  },
  selectPointData: [],
  pointData: [],
  selectIds: [],
  isTablePointShow: false,
  className: ""
});

const {
  queryParams,
  tableData,
  total,
  form,
  isDrawerShow,
  isPointShow,
  rules,
  isEdit,
  selectPointData,
  pointData,
  selectIds,
  isTablePointShow,
  className
} = toRefs(data);

// 进入页面时触发
onMounted(() => queryTable());
function checkDate(rule: any, value: any, callback: any) {
  console.log(form.value);
  if (value === "") {
    callback(new Error("请选择要下线生效时间范围"));
  } else if (value === "NO") {
    if (!form.value?.timeRangeType) {
      callback(new Error("请选择时间范围类型"));
    } else if (form.value?.date?.length === 0) {
      callback(new Error("请选择时间范围"));
    } else {
      callback();
    }
  } else {
    callback();
  }
}

const tagBgColorList = {
  一级报警: "#E02B2B",
  二级报警: "#FF771E",
  三级报警: "#F1B11A",
  四级报警: "#4A9BFF"
};

const queryTable = async () => {
  const data = await queryShieldRulesListApi(queryParams.value);
  tableData.value = data?.data;
  total.value = data?.total;
};

/** 启用/禁用按钮操作 */
const handleEnable = row => {
  const { enableStatus, id, ruleName } = row;
  PxMessageBox.confirm(`是否确认${enableStatus === "ON" ? "禁用" : "启用"}下线规则名称为${ruleName}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await updateShieldRulesApi({ id, enableStatus: enableStatus === "ON" ? "OFF" : "ON" });
      PxMessage.success(`${enableStatus === "ON" ? "禁用" : "启用"}成功`);
      queryTable();
    })
    .catch(() => {});
};

const handleBatchDeletePoint = () => {
  selectPointData.value = selectPointData.value.filter(item => selectIds.value.indexOf(item.point) === -1);
};

const handleDelete = async row => {
  try {
    const { ruleId, ruleName } = row;
    PxMessageBox.confirm(`是否确认删除报警下线规则名称为${ruleName}的数据项？`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    }).then(async () => {
      await deleteShieldRulesApi({ ruleId });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      queryTable();
    });
  } catch (error) {
    console.log(error);
  }
};

// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  form.value.className = val;
  if (!isOnlyClass) {
    selectPointData.value = [];
    selectIds.value = [];
  }
};

const handleUpdate = async row => {
  try {
    const { ruleId } = row;
    const data = await queryShieldRuleByRuleId({ ruleId });
    // const { pushChannel } = data;
    // form.value = { ...data, pushChannel: pushChannel.split(",") };
    const { startTime, endTime, shieldPointList } = data;
    const date = startTime && endTime ? [startTime, endTime] : [];
    selectPointData.value = shieldPointList;
    form.value = { ...data, date };

    isDrawerShow.value = true;
    isEdit.value = true;
  } catch (error) {
    console.log(error);
  }
};

// 表格多选框选中-点位
const selectionPointChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.point) {
      selectIds.value.push(item.point);
    }
  });
};

const handleDeletePoint = index => {
  selectPointData.value.splice(index, 1);
};

const handleShowPointList = async row => {
  isTablePointShow.value = true;
  const { shieldPointList } = await queryShieldRuleByRuleId({ ruleId: row.ruleId });
  pointData.value = shieldPointList || [];
};

const handleCloseTablePoint = () => {
  isTablePointShow.value = false;
  pointData.value = [];
};

// 关闭选择工具的弹窗并且拿到选择的数据
const closeDialog = (val?: any) => {
  if (val) {
    selectPointData.value = selectPointData.value?.concat(val)?.filter((obj, index, self) => {
      return self.map(x => x.id).indexOf(obj.id) === index;
    });
  }
  isPointShow.value = false;
};

const handelCancel = () => {
  reset();
  isDrawerShow.value = false;
};
/** 表单重置 */
function reset() {
  form.value = {
    id: "",
    ruleId: "",
    date: [],
    ruleDesc: "",
    ruleName: "",
    isForeverShield: "",
    timeRangeType: "",
    enableStatus: ""
  };
  selectIds.value = [];
  selectPointData.value = [];
  proxy.resetForm("formRef");
  isEdit.value = false;
}

const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (selectPointData.value?.length === 0) {
        PxMessage.warning("请至少选择一个点位");
        return;
      }
      const { date, time, timeRangeType, isForeverShield } = form.value;
      const idList = selectPointData.value.map(item => item.point);
      const [startTime, endTime] = isForeverShield === "NO" ? date : [];
      // const [relativeStart, relativeEnd] = time;
      let data = { ...toRaw(form.value), startTime, endTime, shieldCondition: idList.join(",") };
      // if (timeRangeType === "RELATIVE ") {
      //   data.startTime = relativeStart;
      //   data.endTime = relativeEnd;
      // }
      delete data.date;
      if (isEdit.value) {
        await updateShieldRulesApi(data);
        PxMessage.success("修改成功");
      } else {
        await addShieldRulesApi(data);
        PxMessage.success("新增成功");
      }
      handelCancel();
      queryTable();
    }
  });
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");
.status {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: left;

  .circle {
    width: 6px;
    height: 6px;
    margin-right: 8px;
    border-radius: 50%;
  }

  .green {
    background-color: #10b981;
  }

  .red {
    background-color: #ef4444;
  }
}

:deep(.px-radio) {
  margin-right: 16px;
}
</style>
